import React, { useEffect, useState } from "react";
import { ListRawState, SearchRawState } from "../../types";
import { addList, deleteList, deleteListBySelected, editList, getList } from "../../api";
import {
  Table,
  Button,
  Space,
  Modal,
  message as antdMessage,
  message,
  Tag,
} from "antd";
import qs from 'qs'
import ModalTable from "../../components/modalTable";
import MySearch from "../../components/search";
import { useLocation, useSearchParams } from "react-router-dom";
const Index: React.FC = () => {
  // 1. 状态容器
  const [list, setList] = useState<ListRawState[]>([]);
  // 2. 请求函数
  const fetchList = async (params?: SearchRawState) => {
    // 2-2 发送请求
    const resp = await getList(params);
    // 2-2 保存数据
    setList(resp.data.data);
  };
 
  // 4. 表格列数据
  const columns = [
    {
      key: "id",
      title: "字典编号",
      dataIndex: "id",
    },
    {
      key: "name",
      title: "字典名称",
      dataIndex: "name",
    },
    {
      key: "type",
      title: "字典类型",
      dataIndex: "type",
    },
    {
      key: "state",
      title: "状态",
      dataIndex: "state",
    },
    {
      key: "tip",
      title: "备注",
      dataIndex: "tip",
    },
    {
      key: "createDateTime",
      title: "创建时间",
      dataIndex: "createDateTime",
    },
    {
      key: "updateDateTime",
      title: "修改时间",
      dataIndex: "updateDateTime",
    },
    {
      key: "id",
      title: "操作",
      render(item: ListRawState) {
        return (
          <Space>
            <Button type="primary" onClick={() => openEditModal(item)}>
              编辑
            </Button>
            <Button type="primary" danger onClick={() => handleDelete(item.id)}>
              删除
            </Button>
          </Space>
        );
      },
    },
  ];
  // 5. 定义单项删除函数
  const handleDelete = (id: string) => {
    // 二次确定
    Modal.confirm({
      title: "警告",
      content: `你确认要删除字典编号为${id}的项目?`,
      okText: "确定",
      cancelText: "取消",
      async onOk() {
        // 权限
        const role = localStorage.getItem("role");
        if (role !== "admin") {
          antdMessage.error(
            "非常遗憾， 你没有权限， 你体验一下删除效果就可以了！！"
          );
          return;
        }
        // 确定删除
        const resp = await deleteList(id);
        const { message, code, data } = resp.data;
        antdMessage.success(message);
        fetchList();
      },
      onCancel() {
        console.log("2");
      },
    });
  };
  // 6. 定义临时选中项目的 keys 容器
  const [keys, setKeys] = useState<string[]>([]);
  // 7. 定义选中删除函数
  const handleDeleteBySelected = () => {
    // 二次确定
    Modal.confirm({
      title: "警告",
      content: (
        <div>
          你确认要删除字典编号为
          {keys.map((v, i) => (
            <Tag key={i}>{v}</Tag>
          ))}
          的项目?
        </div>
      ),
      okText: "确定",
      cancelText: "取消",
      async onOk() {
        // 权限
        const role = localStorage.getItem("role");
        if (role !== "admin") {
          antdMessage.error(
            "非常遗憾， 你没有权限， 你体验一下删除效果就可以了！！"
          );
          return;
        }
        // 确定删除
        const resp = await deleteListBySelected(keys);
        const { message, code } = resp.data;
        antdMessage.success(message);
        fetchList();
      },
      onCancel() {
        console.log("2");
      },
    });
  };
  /************************** 弹框组件 ******************************/
  // 1. 状态
  const [show, setShow] = useState(false);
  const [editShow, setEditShow] = useState(false);
  // 2. 弹框方法
  const openModal = () => setShow(true);
  const closeModal = () => setShow(false);
  const openEditModal = (item: ListRawState) => {
    setEditItem(item);
    setEditShow(true);
  };
  const closeEditModal = () => setEditShow(false);
  // 3. 确定事件
  const onAddOK = async (item: ListRawState) => {
    closeModal();
    const resp = await addList(item);
    antdMessage.success(resp.data.message)
    fetchList()
  };
  const onEditOK = async (item: ListRawState) => {
    closeEditModal();
    const resp = await editList(item.id, item);
    antdMessage.success(resp.data.message)
    fetchList()
    
  };
  // 4. 当前点击的修改的数据
  const [editItem, setEditItem] = useState<ListRawState>();
  /************************** 搜索功能 ******************************/
  const [searchParams, setSearchParams] = useSearchParams();
  const location = useLocation();
  const obj = qs.parse(location.search.slice(1))
  const onSearch = async (params: SearchRawState) => {
    setSearchParams({
      ...params
    })
    // 请求后端接口
    const resp = await fetchList(params)
  }
   // 3. 副作用
   useEffect(() => {
    fetchList({
      value: obj.value as string,
      type: obj.type as string,
      start: obj.start as string || "",
      end: obj.end as string || "",
    });
  }, []);
  return (
    <div>
      <MySearch onSearch={(params) => onSearch(params) } initValue={ obj }></MySearch>
      <Space>
        <Button type="primary" onClick={() => openModal()}>
          新增
        </Button>
        <Button
          type="primary"
          danger
          onClick={() => handleDeleteBySelected()}
          disabled={keys.length === 0}
        >
          删除所选
        </Button>
      </Space>

      <Table
        dataSource={list}
        columns={columns}
        rowKey="id"
        pagination={{
          pageSize: 3,
        }}
        rowSelection={{
          onChange(keys) {
            setKeys(keys as string[]);
          },
        }}
      ></Table>
      {/* 新增 */}
      <ModalTable
        show={show}
        onOK={onAddOK}
        onCancel={closeModal}
        title="新增数据"
      ></ModalTable>
      {/* 编辑 */}
      <ModalTable
        show={editShow}
        onOK={onEditOK}
        onCancel={closeEditModal}
        title="编辑数据"
        editItem={editItem}
      ></ModalTable>
    </div>
  );
};

export default Index;
